<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */
namespace App\Service;

use App\Model\Demo;
use Grpc\Base\Common\V1\GetUserRequest;
use Grpc\Base\Common\V1\GetUserResponse;
use Hyperf\Grpc\StatusCode;
use Hyperf\GrpcServer\Exception\GrpcException;

class GetUserService extends BaseService
{
    public function checkRequest(GetUserRequest $request): void
    {
        if (empty($request->getUserId())) {
            throw new GrpcException('user_id is empty', StatusCode::INVALID_ARGUMENT);
        }
    }

    public function handle(GetUserRequest $request): GetUserResponse
    {
        // business logic ..

        $user = $this->getUser($request->getUserId());

        $response = new GetUserResponse();
        $response->setUsername($user['username']);
        $response->setSex($user['sex']);
        return $response;
    }

    public function getUser(int $userId): array
    {

        $maps = [
            1 => [
                'username' => 'lichao',
                'sex' => 1,
            ],
            2 => [
                'username' => 'lili',
                'sex' => 2,
            ],
        ];
        if (! isset($maps[$userId])) {
            throw new GrpcException('user_id is empty', StatusCode::NOT_FOUND);
        }
        return $maps[$userId];
    }
}
